﻿using Demo.Api.Config;
using Demo.Interface.BasicData;
using Demo.Model.Entitys.BasicData;
using Demo.Model.Other;
using Demo.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using SqlSugar;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Demo.Api.Controllers.Commin
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    
    public class WebApiBaseController : Controller
    {
        private readonly IRedis _redis;
        private readonly ILogger _logger;
        //private readonly JWTTokenOptions _JWTTokenOptions = IOptionsMonitor<JWTTokenOptions>.CurrentValue;
        //private readonly IOptionsMonitor<JWTTokenOptions> jwtTokenOptions;
        //private readonly IPrincipalAccessor _principalAccessor;
        private readonly ILogService _logService;
        private readonly ISqlSugarClient _db;
        public WebApiBaseController()
        {
            _redis = new Redis();
        }


        /// <summary>
        /// Action方法调用之前执行
        /// </summary>
        /// <param name="context"></param>
        public override async void OnActionExecuting(ActionExecutingContext context)
        {

            //string token = IHttpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            //string aa = HttpContext.Request.Headers["Request URL"].ToString();
            string token = HttpContext.Request.Headers["Authorization"].ToString();
            token = token.Replace("Bearer  ", "");
            var claim = User.Claims.FirstOrDefault();
            if (string.IsNullOrEmpty(token))
            {
                //var res = Task<ApiResult>.Run(() =>
                //{
                //    ResultHelper.Error("Token不能为空");
                //});
                context.Result = Ok(new { isSuccess = false, msg = "Token不能为空" });
                return ;
            }
            else
            {

                #region 验证token，并续签redis中token时间
                try
                {

                    JWTTokenOptions jWTTokenOptions = new JWTTokenOptions();

                    JwtSecurityToken jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
                    if (jwtToken != null)
                    {
                        #region 注释代码验证鉴权
                        //var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ////DateTime jwtTime = jwtToken.ValidFrom;
                        //var ss = jwtToken.ValidFrom;
                        //var enddate =jwtToken.Claims.First(t=>t.Type=="Enddate").Value;
                        //if ( string.CompareOrdinal(enddate,time) >0 )
                        //{
                        //    //获取UserId
                        //    var Name = jwtToken.Claims.First(t => t.Type == "Name").Value;
                        //    var redistoken = _redis.GetAsync("Zhao_" + Name);
                        //    if (redistoken != null)
                        //    {
                        //        //每次请求重新设置redis缓存时间
                        //        await _redis.ExpireAtAsync("Zhao_" + Name, DateTime.Now.AddMinutes(2));
                        //    }
                        //    else
                        //    {
                        //        context.Result = Ok(new { isSuccess = false, msg = "用户令牌Token超时失效" });
                        //        return;
                        //    }

                        //}
                        //else
                        //{
                        //    context.Result = Ok(new { isSuccess = false, msg = "用户令牌Token超时失效" });
                        //    return;
                        //}
                        //var aa = jWTTokenOptions.GqTime; 
                        #endregion
                        //获取redis中token
                        var Name = jwtToken.Claims.First(t => t.Type == "Name").Value;
                        var redistoken="";
                        redistoken = _redis.Get("Zhao_" + Name).Replace("Bearer  ", "");
                        
                        if (redistoken == token)
                        {
                            //判断redis剩余时间
                            var remainingtime = _redis.GetRemainingTime("Zhao_" + Name);
                            if (remainingtime / 60 < 30)//低于30分钟在访问重定义redistoken时间
                            {
                                //续接redis中token时间
                                await _redis.ExpireAtAsync("Zhao_" + Name, DateTime.Now.AddMinutes(60));
                            }

                        }
                        else
                        {
                            context.Result = Ok(new { isSuccess = false, msg = "用户令牌Token超时失效" });
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Result = Ok(new { isSuccess = false, msg = ex.Message });
                    return;
                } 
                #endregion

                //日志写入
                var descriptor = context.ActionDescriptor as ControllerActionDescriptor;

                string param = string.Empty;
                string globalParam = string.Empty;

                foreach (var arg in context.ActionArguments)
                {
                    string value = Newtonsoft.Json.JsonConvert.SerializeObject(value: arg.Value);
                    param += $"{arg.Key} : {value} \r\n";
                    globalParam += value;
                }
                Console.WriteLine($"webapi方法名称:【{descriptor.ActionName}】接收到参数为：{param}");               
                var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
               // claim = this.User.FindFirst(t => true);
               // string czzh = claim.Value;
                var czkzq = this.GetType();
                Log log = new Log();
                log.Ip = ip;
                //log.Czzh = czzh;
                log.DateTime= Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                log.OpenType=descriptor.ActionName;
                log.CzLj = czkzq.ToSqlValue();
                //var aa = _logService.AddLog(log);
            }



        }
       
        /// 获取基本信息写入日志
        /// </summary>
        /// <param name="context"></param>
        //public  override async void  OnActionExecuting(ActionExecutingContext context) 
        //{
        //    //获取token与redis中对应
        //    //string value = HttpContext.Current.Request.Headers["name"];
        //    //从请求中获取 Header 并注入 WebApiClient Header 中传递

        //    //var headers = _httpContextAccessor.HttpContext.Request.Headers;


        //    //var res = Task.Run(() =>
        //    //{
        //    //    return ResultHelper.Error("请输入Jwt凭证");
        //    //});
        //    //return Ok(res);
        //    //var model = _warehouseService.wareHouseAdd(wareHouse);
        //    //return await res;
        //    //获取redis的toke
        //    var claim = this.User.FindFirst(t => true);
        //    string czzh = claim.Value;
        //    var czkzq = this.GetType();
        //    var ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
        //}



    }
    
}
